import { useEffect, useState } from 'react';
import { get } from '../services/api';
import CommonTable from '../components/CommonTable';
import ClassForm from '../components/ClassForm';
import EnrollmentModal from '../components/EnrollmentModal';
import { Button, Space } from 'antd';
import { UserAddOutlined } from '@ant-design/icons';

function ClassesPage() {
  const [classes, setClasses] = useState([]);
  const [loading, setLoading] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [enrollmentModal, setEnrollmentModal] = useState({
    visible: false,
    classInfo: null
  });

  const fetchClasses = async () => {
    setLoading(true);
    try {
      const response = await get('classes');
      setClasses(response.data || response);
    } catch (error) {
      console.error('获取班级数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchClasses();
  }, []);

  const handleEnrollment = (record) => {
    setEnrollmentModal({
      visible: true,
      classInfo: record
    });
  };

  const handleEnrollmentClose = (needRefresh) => {
    setEnrollmentModal({
      visible: false,
      classInfo: null
    });
    if (needRefresh) {
      fetchClasses();
    }
  };

  const columns = [
    {
      title: '班级编号',
      dataIndex: 'class_id',
      key: 'class_id',
      sorter: (a, b) => a.class_id - b.class_id,
      width: '12%',
    },
    {
      title: '班级名称',
      dataIndex: 'class_name',
      key: 'class_name',
      sorter: (a, b) => a.class_name.localeCompare(b.class_name),
      width: '18%',
    },
    {
      title: '学期',
      dataIndex: 'semester',
      key: 'semester',
      sorter: (a, b) => a.semester.localeCompare(b.semester),
      width: '15%',
    },
    {
      title: '教室',
      dataIndex: 'location',
      key: 'location',
      width: '12%',
    },
    {
      title: '课程编号',
      dataIndex: 'course_id',
      key: 'course_id',
      width: '12%',
    },
    {
      title: '学生人数',
      dataIndex: 'students',
      key: 'student_count',
      render: (students) => students ? students.length : 0,
      width: '10%',
    },
    {
      title: '操作',
      key: 'action',
      width: '21%',
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="primary"
            icon={<UserAddOutlined />}
            onClick={() => handleEnrollment(record)}
            size="small"
          >
            选课管理
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <>
      <CommonTable
        title="班级管理"
        columns={columns}
        dataSource={classes}
        loading={loading}
        rowKey="class_id"
        searchFields={['class_id', 'class_name', 'semester', 'location']}
        onAdd={() => setShowForm(true)}
        extraContent={
          showForm && (
            <ClassForm 
              onClose={() => setShowForm(false)} 
              onSuccess={fetchClasses}
            />
          )
        }
      />
      
      <EnrollmentModal
        visible={enrollmentModal.visible}
        onClose={handleEnrollmentClose}
        classInfo={enrollmentModal.classInfo}
      />
    </>
  );
}

export default ClassesPage;